<script>
import request from "@/utils/request.js";
import { Delete } from "@element-plus/icons-vue";
export default {

  data() {
    return {
      loginLogs: [], // 登录日志列表
      pageNum: 1,    // 当前页码
      pageSize: 12,  // 每页显示条数
      total: 0,      // 总记录数
      Delete:Delete,
    };
  },
  created() {
    this.fetchLoginLogs(); // 页面加载时获取数据
  },
  methods: {
    // 获取登录日志分页数据
    async fetchLoginLogs() {
      try {
        const res = await request.get("/loginlog/all/page", {
          params: { pageNum: this.pageNum, pageSize: this.pageSize },
        });
        // 检查 res 是否存在且为对象
        if (res && typeof res === 'object') {
          // 兼容后端返回的数据结构
          const list = res.list || res.data?.list || [];
          const total = res.total || res.data?.total || 0;
          const pageNum = res.pageNum || res.data?.pageNum || 1;

          // 确保 list 是数组
          if (Array.isArray(list)) {
            this.loginLogs = list.map(log => ({
              ...log,
              loginTime: this.formatDate(log.loginTime), // 格式化时间
            }));
            this.total = total; // 设置总记录数
            this.pageNum = pageNum; // 设置当前页码
          } else {
            console.error("后端返回的 list 数据不是数组");
            this.loginLogs = []; // 设置为空数组
            this.total = 0; // 设置总记录数为 0
          }
        } else {
          console.error("后端返回的数据结构不符合预期");
          this.loginLogs = []; // 设置为空数组
          this.total = 0; // 设置总记录数为 0
        }
      } catch (error) {
        console.error("获取登录日志失败", error);
        this.loginLogs = []; // 设置为空数组
        this.total = 0; // 设置总记录数为 0
      }
    },
    // 时间格式化函数
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    // 分页切换事件
    handlePageChange(page) {
      this.pageNum = page;
      this.fetchLoginLogs();
    },
    // 删除登录日志
    async deleteLoginLog(id) {
      try {
        // 增加用户确认提示
        const confirm = await this.$confirm('确定要删除该登录日志吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        if (confirm) {
          await request.delete(`/loginlog/delete/${id}`); // 调用后端删除接口
          this.$message.success("删除成功");
          this.fetchLoginLogs(); // 刷新数据
        }
      } catch (error) {
        console.error("删除登录日志失败", error);
        if (error.response && error.response.status === 404) {
          this.$message.error("该登录日志不存在");
        } else {
          this.$message.error("删除失败，请稍后重试");
        }
      }
    },
  },
};
</script>

<template>
  <div class="login-log-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>登录日志管理</h1>
    </div>

    <!-- 表格展示 -->
    <div class="table-container">
      <el-table :data="loginLogs" border style="width: 100%;" class="custom-table">
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="username" label="用户账号" width="200px" align="center"></el-table-column>
        <el-table-column prop="nickname" label="用户昵称" width="200px" align="center"></el-table-column>
        <el-table-column prop="loginTime" label="登录时间" width="380px" align="center"></el-table-column>
        <el-table-column prop="loginIp" label="登录IP" width="300px" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="120px" align="center"></el-table-column>
        <el-table-column label="操作" width="auto" align="center">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteLoginLog(scope.row.id)" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        class="pagination"
        background
        @current-change="handlePageChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper, ->, total"
      ></el-pagination>
    </div>
  </div>
</template>

<style scoped>
.login-log-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 隐藏滚动条但保持滚动功能 */
:deep(.el-scrollbar__bar) {
  display: none;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.table-container {
  margin-bottom: 20px;
}

.custom-table {
  border-radius: 4px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.custom-table :deep(.el-table__row) {
  transition: background-color 0.3s;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  margin: 0;
}
</style>